<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="名称" :label-width="labelWidth" prop="name">
        <ElInput v-model="form.name" />
      </ElFormItem>
      <ElFormItem label="地址" :label-width="labelWidth" prop="url">
        <ElInput v-model="form.url" />
      </ElFormItem>
      <ElFormItem label="预览图" :label-width="labelWidth" prop="icon">
        <UploadImg v-model:image-url="form.icon!" :api="uploadAvatar" :fileSize="10">
          <template #tip>图片最大为 10M</template>
        </UploadImg>
      </ElFormItem>
      <ElFormItem label="是否启用" :label-width="labelWidth" prop="active">
        <el-select filterable v-model="form.active" :clearable="true" :fit-input-width="true">
          <el-option v-for="item in LayerConfig.ActiveEnum" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { LayerConfig, getLayerConfigDetail, saveOrUpdateLayerConfig, existName, existUrl } from '@api/tby/common/layerConfig'
import { FormType } from '@/enums'
import { uiUpload } from '@api/upload'
import UploadImg from '@/components/Upload/Img.vue'

const labelWidth = 150
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<LayerConfig.Form>>({})

// 上传头像
function uploadAvatar(formData: FormData) {
  return uiUpload('avatar', formData)
}

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const validateName = (rule: any, value: any, callback: any) => {
  existName(value, form.value?.id).then(resp => {
    if (!value) {
      return callback()
    }
    if (resp.data) {
      callback(new Error('图层名已存在'))
    } else {
      callback()
    }
  })
}

const validateUrl = (rule: any, value: any, callback: any) => {
  existUrl(value, form.value?.id).then(resp => {
    if (!value) {
      return callback()
    }
    if (resp.data) {
      callback(new Error('图层地址已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入图层名', trigger: 'blur' },
    { max: 20, message: '图层名最大32个字符', trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入图层地址', trigger: 'blur' },
    { max: 64, message: '图层地址最大64个字符', trigger: 'blur' },
    { validator: validateUrl, trigger: 'blur' }
  ],
  icon: [{ required: true, message: '请上传预览图', trigger: 'blur' }],
  active: [{ required: true, message: '请选择是否启用', trigger: 'blur' }]
})

const open = async (type: FormType, id?: number) => {
  form.value = {}
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getLayerConfigDetail(id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateLayerConfig(formData).then(response => {
      console.log(response)
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
